import React, { useState, useEffect, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import axios from 'axios'
import { AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai'
import './Chongzhi.css'

export default function Chongzhi() {
    const navigate = useNavigate()
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [success, setSuccess] = useState('')
    
    // 重置密码步骤
    const [step, setStep] = useState(1) // 1: 手机/邮箱验证, 2: 设置新密码
    
    // 表单数据
    const [formData, setFormData] = useState({
        contact: '', // 手机号或邮箱
        verificationCode: '',
        captcha: '', // 图灵码
        password: '',
        confirmPassword: ''
    })
    
    // 错误信息
    const [errors, setErrors] = useState({})
    
    // 验证码倒计时
    const [countdown, setCountdown] = useState(0)
    const timerRef = useRef(null)
    
    // 密码可见性
    const [showPassword, setShowPassword] = useState(false)
    const [showConfirmPassword, setShowConfirmPassword] = useState(false)
    
    // 随机图灵码
    const [captchaCode, setCaptchaCode] = useState('')
    const [captchaImage, setCaptchaImage] = useState('')
    
    // 密码强度
    const [passwordStrength, setPasswordStrength] = useState({
        score: 0,
        hasLength: false,
        hasUpperCase: false,
        hasLowerCase: false,
        hasNumber: false,
        hasSymbol: false,
        noSpace: true,
        noRepeat: true,
        noConsecutive: true,
    })
    
    // 判断是手机号还是邮箱
    const isPhoneNumber = (input) => {
        // 中国大陆手机号格式：1开头的11位数字
        const phoneRegex = /^1[3-9]\d{9}$/
        return phoneRegex.test(input)
    }
    
    const isEmail = (input) => {
        // 邮箱基本格式检查
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        return emailRegex.test(input)
    }
    
    // 生成随机图灵验证码
    const generateCaptcha = () => {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
        let captcha = ''
        for (let i = 0; i < 4; i++) {
            captcha += chars.charAt(Math.floor(Math.random() * chars.length))
        }
        setCaptchaCode(captcha)
        generateCaptchaImage(captcha)
    }
    
    // 生成图灵验证码图片
    const generateCaptchaImage = (code) => {
        const canvas = document.createElement('canvas')
        canvas.width = 100
        canvas.height = 40
        const ctx = canvas.getContext('2d')
        
        // 填充白色背景
        ctx.fillStyle = '#f0f0f0'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        
        // 添加干扰线
        for (let i = 0; i < 3; i++) {
            ctx.strokeStyle = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255},0.5)`
            ctx.beginPath()
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
            ctx.stroke()
        }
        
        // 添加干扰点
        for (let i = 0; i < 50; i++) {
            ctx.fillStyle = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255},0.5)`
            ctx.beginPath()
            ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2)
            ctx.fill()
        }
        
        // 绘制验证码
        ctx.font = 'bold 24px Arial'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        
        for (let i = 0; i < code.length; i++) {
            const charX = (i + 0.5) * (canvas.width / code.length)
            const charY = canvas.height / 2 + Math.random() * 8 - 4
            ctx.fillStyle = `rgb(${Math.floor(Math.random() * 150)},${Math.floor(Math.random() * 150)},${Math.floor(Math.random() * 150)})`
            ctx.save()
            ctx.translate(charX, charY)
            ctx.rotate(Math.random() * 0.4 - 0.2) // 随机旋转 ±0.2 弧度
            ctx.fillText(code[i], 0, 0)
            ctx.restore()
        }
        
        // 转换为 base64 图片
        const dataURL = canvas.toDataURL()
        setCaptchaImage(dataURL)
    }
    
    // 初始化和重新生成图灵码
    useEffect(() => {
        generateCaptcha()
    }, [])
    
    // 处理表单输入变化
    const handleInputChange = (e) => {
        const { name, value } = e.target
        setFormData({
            ...formData,
            [name]: value
        })
        
        // 清除相应的错误信息
        if (errors[name]) {
            setErrors({
                ...errors,
                [name]: ''
            })
        }
        
        // 如果是密码，检查强度
        if (name === 'password') {
            checkPasswordStrength(value)
        }
        
        // 清除全局错误和成功消息
        setError('')
        setSuccess('')
    }
    
    // 检查密码强度
    const checkPasswordStrength = (password) => {
        const hasLength = password.length >= 8 && password.length <= 16
        const hasUpperCase = /[A-Z]/.test(password)
        const hasLowerCase = /[a-z]/.test(password)
        const hasNumber = /[0-9]/.test(password)
        const hasSymbol = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)
        const noSpace = !/\s/.test(password)
        const noRepeat = !/(.)\1\1/.test(password) // 不能有连续重复3个及以上的字符
        const noConsecutive = !/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789|890)/i.test(password) // 不能有连续3个及以上的字符或数字
        
        // 计算密码强度分数 (0-5)
        let score = 0
        if (hasLength) score++
        if (hasUpperCase) score++
        if (hasLowerCase) score++
        if (hasNumber) score++
        if (hasSymbol) score++
        if (!noSpace || !noRepeat || !noConsecutive) score = Math.max(1, score - 2)
        
        // 更新密码强度状态
        setPasswordStrength({
            score,
            hasLength,
            hasUpperCase,
            hasLowerCase,
            hasNumber,
            hasSymbol,
            noSpace,
            noRepeat,
            noConsecutive
        })
    }
    
    // 获取密码强度描述
    const getPasswordStrengthText = () => {
        const { score } = passwordStrength
        if (score <= 1) return "弱"
        if (score <= 3) return "中"
        return "强"
    }
    
    // 获取密码强度颜色
    const getPasswordStrengthColor = () => {
        const { score } = passwordStrength
        if (score <= 1) return "#ff4d4f"
        if (score <= 3) return "#faad14"
        return "#52c41a"
    }
    
    // 发送验证码
    const sendVerificationCode = () => {
        const { contact } = formData
        
        // 验证手机号或邮箱
        if (!contact) {
            setErrors({
                ...errors,
                contact: '请输入手机号或邮箱'
            })
            return
        }
        
        if (!isPhoneNumber(contact) && !isEmail(contact)) {
            setErrors({
                ...errors,
                contact: '请输入有效的手机号或邮箱'
            })
            return
        }
        
        // 验证图灵码
        if (!formData.captcha) {
            setErrors({
                ...errors,
                captcha: '请输入验证码'
            })
            return
        }
        
        if (formData.captcha.toLowerCase() !== captchaCode.toLowerCase()) {
            setErrors({
                ...errors,
                captcha: '验证码不正确'
            })
            // 刷新图灵码
            generateCaptcha()
            return
        }
        
        // 发送验证码请求
        setLoading(true)
        
        const requestData = {
            ...(isPhoneNumber(contact) ? { phone: contact } : { email: contact })
        }
        
        axios.post('http://localhost:3001/lxt/send-reset-code', requestData)
            .then(response => {
                console.log('验证码发送成功:', response.data)
                setSuccess(`验证码已发送到${isPhoneNumber(contact) ? '手机' : '邮箱'}，请查收`)
                // 开始倒计时
                setCountdown(60)
            })
            .catch(err => {
                console.error('验证码发送失败:', err)
                if (err.response && err.response.data && err.response.data.msg) {
                    setError(`发送失败: ${err.response.data.msg}`)
                } else {
                    setError('验证码发送失败，请稍后再试')
                }
                // 刷新图灵码
                generateCaptcha()
            })
            .finally(() => {
                setLoading(false)
            })
    }
    
    // 验证验证码，进入下一步
    const verifyCodeAndProceed = (e) => {
        e.preventDefault()
        
        const { contact, verificationCode, captcha } = formData
        
        // 表单验证
        const newErrors = {}
        let isValid = true
        
        if (!contact) {
            newErrors.contact = '请输入手机号或邮箱'
            isValid = false
        } else if (!isPhoneNumber(contact) && !isEmail(contact)) {
            newErrors.contact = '请输入有效的手机号或邮箱'
            isValid = false
        }
        
        if (!verificationCode) {
            newErrors.verificationCode = '请输入验证码'
            isValid = false
        } else if (verificationCode.length !== 6) {
            newErrors.verificationCode = '验证码应为6位'
            isValid = false
        }
        
        if (!captcha) {
            newErrors.captcha = '请输入图形验证码'
            isValid = false
        } else if (captcha.toLowerCase() !== captchaCode.toLowerCase()) {
            newErrors.captcha = '图形验证码不正确'
            isValid = false
            // 刷新图灵码
            generateCaptcha()
        }
        
        if (!isValid) {
            setErrors(newErrors)
            return
        }
        
        // 验证验证码
        setLoading(true)
        
        const requestData = {
            ...(isPhoneNumber(contact) ? { phone: contact } : { email: contact }),
            code: verificationCode
        }
        
        axios.post('http://localhost:3001/lxt/verify-reset-code', requestData)
            .then(response => {
                console.log('验证码验证成功:', response.data)
                // 进入下一步
                setStep(2)
                setError('')
                setSuccess('验证成功，请设置新密码')
            })
            .catch(err => {
                console.error('验证码验证失败:', err)
                if (err.response && err.response.data && err.response.data.message) {
                    setError(`验证失败: ${err.response.data.message}`)
                } else {
                    setError('验证码验证失败，请确认验证码是否正确')
                }
                // 刷新图灵码
                generateCaptcha()
            })
            .finally(() => {
                setLoading(false)
            })
    }
    
    // 重置密码
    const resetPassword = (e) => {
        e.preventDefault()
        
        const { contact, verificationCode, password, confirmPassword } = formData
        
        // 表单验证
        const newErrors = {}
        let isValid = true
        
        // 验证密码
        if (!password) {
            newErrors.password = '请输入密码'
            isValid = false
        } else {
            // 密码复杂度检查
            const { hasLength, hasUpperCase, hasLowerCase, hasNumber, hasSymbol, noSpace, noRepeat, noConsecutive } = passwordStrength
            const conditionsMet = [hasUpperCase, hasLowerCase, hasNumber, hasSymbol].filter(Boolean).length
            
            if (!hasLength) {
                newErrors.password = '密码长度应在8-16位之间'
                isValid = false
            } else if (conditionsMet < 4) {
                newErrors.password = '密码需包含大写字母、小写字母、数字、特殊符号'
                isValid = false
            } else if (!noSpace) {
                newErrors.password = '密码不能包含空格'
                isValid = false
            } else if (!noRepeat) {
                newErrors.password = '密码不能包含重复的三个及以上字符'
                isValid = false
            } else if (!noConsecutive) {
                newErrors.password = '密码不能包含连续的三个及以上字符或数字'
                isValid = false
            }
        }
        
        // 验证确认密码
        if (!confirmPassword) {
            newErrors.confirmPassword = '请确认密码'
            isValid = false
        } else if (password !== confirmPassword) {
            newErrors.confirmPassword = '两次密码输入不一致'
            isValid = false
        }
        
        if (!isValid) {
            setErrors(newErrors)
            return
        }
        
        // 提交重置密码请求
        setLoading(true)
        
        const requestData = {
            ...(isPhoneNumber(contact) ? { phone: contact } : { email: contact }),
            code: verificationCode,
            newPassword: password
        }
        
        axios.post('http://localhost:3001/lxt/reset-password', requestData)
            .then(response => {
                console.log('密码重置成功:', response.data)
                setSuccess('密码重置成功！3秒后跳转到登录页面...')
                
                // 3秒后跳转到登录页
                setTimeout(() => {
                    navigate('/login')
                }, 3000)
            })
            .catch(err => {
                console.error('密码重置失败:', err)
                if (err.response && err.response.data && err.response.data.msg) {
                    setError(`重置失败: ${err.response.data.msg}`)
                } else {
                    setError('密码重置失败，请稍后再试')
                }
            })
            .finally(() => {
                setLoading(false)
            })
    }
    
    // 倒计时逻辑
    useEffect(() => {
        if (countdown > 0) {
            timerRef.current = setTimeout(() => {
                setCountdown(countdown - 1)
            }, 1000)
        }
        
        return () => {
            if (timerRef.current) {
                clearTimeout(timerRef.current)
            }
        }
    }, [countdown])
    
    return (
        <div className="reset-password-container">
            <div className="reset-password-wrapper">
                <div className="reset-password-form">
                    <div className="reset-header">
                        <h2>重置密码</h2>
                        <Link to="/login" className="login-link">返回登录</Link>
                    </div>
                    
                    {/* 全局错误提示 */}
                    {error && (
                        <div className="error-alert">
                            {error}
                        </div>
                    )}
                    
                    {/* 全局成功提示 */}
                    {success && (
                        <div className="success-alert">
                            {success}
                        </div>
                    )}
                    
                    {/* 第一步: 验证手机号/邮箱 */}
                    {step === 1 && (
                        <form onSubmit={verifyCodeAndProceed}>
                            <div className="form-group">
                                <label htmlFor="contact">手机号/邮箱</label>
                                <input
                                    id="contact"
                                    type="text"
                                    name="contact"
                                    value={formData.contact}
                                    onChange={handleInputChange}
                                    placeholder="请输入手机号或邮箱"
                                    disabled={loading}
                                />
                                {errors.contact && <span className="error-message">{errors.contact}</span>}
                            </div>
                            
                            <div className="form-group verification-group">
                                <label htmlFor="verificationCode">验证码</label>
                                <div className="verification-input-group">
                                    <input
                                        id="verificationCode"
                                        type="text"
                                        name="verificationCode"
                                        value={formData.verificationCode}
                                        onChange={handleInputChange}
                                        placeholder="请输入验证码"
                                        maxLength={6}
                                        disabled={loading}
                                    />
                                    <button
                                        type="button"
                                        className="verification-code-btn"
                                        onClick={sendVerificationCode}
                                        disabled={countdown > 0 || loading}
                                    >
                                        {countdown > 0 ? `${countdown}秒后重发` : "获取验证码"}
                                    </button>
                                </div>
                                {errors.verificationCode && (
                                    <span className="error-message">{errors.verificationCode}</span>
                                )}
                            </div>
                            
                            <div className="form-group captcha-group">
                                <label htmlFor="captcha">图形验证码</label>
                                <div className="captcha-input-group">
                                    <input
                                        id="captcha"
                                        type="text"
                                        name="captcha"
                                        value={formData.captcha}
                                        onChange={handleInputChange}
                                        placeholder="请输入图形验证码"
                                        maxLength={4}
                                        disabled={loading}
                                    />
                                    <div 
                                        className="captcha-image"
                                        onClick={generateCaptcha}
                                        title="点击刷新"
                                    >
                                        {captchaImage && <img src={captchaImage} alt="验证码" />}
                                    </div>
                                </div>
                                {errors.captcha && <span className="error-message">{errors.captcha}</span>}
                            </div>
                            
                            <button
                                type="submit"
                                className="submit-btn"
                                disabled={loading}
                            >
                                {loading ? "验证中..." : "下一步"}
                            </button>
                        </form>
                    )}
                    
                    {/* 第二步: 设置新密码 */}
                    {step === 2 && (
                        <form onSubmit={resetPassword}>
                            <div className="form-group password-group">
                                <label htmlFor="password">新密码</label>
                                <div className="password-input-wrapper">
                                    <input
                                        id="password"
                                        type={showPassword ? "text" : "password"}
                                        name="password"
                                        value={formData.password}
                                        onChange={handleInputChange}
                                        placeholder="请设置8-16位密码"
                                        disabled={loading}
                                    />
                                    <span
                                        className="toggle-password"
                                        onClick={() => setShowPassword(!showPassword)}
                                    >
                                        {showPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />}
                                    </span>
                                </div>
                                {formData.password && (
                                    <div className="password-strength">
                                        <div className="strength-label">密码强度：</div>
                                        <div 
                                            className="strength-value" 
                                            style={{ color: getPasswordStrengthColor() }}
                                        >
                                            {getPasswordStrengthText()}
                                        </div>
                                        <div className="strength-meter">
                                            <div 
                                                className="strength-meter-fill" 
                                                style={{ 
                                                    width: `${(passwordStrength.score / 5) * 100}%`,
                                                    backgroundColor: getPasswordStrengthColor()
                                                }}
                                            ></div>
                                        </div>
                                    </div>
                                )}
                                {errors.password && <span className="error-message">{errors.password}</span>}
                            </div>
                            
                            <div className="password-rules">
                                <div className={`rule ${passwordStrength.hasLength ? 'valid' : ''}`}>
                                    ✓ 密码长度为8-16位
                                </div>
                                <div className={`rule ${[passwordStrength.hasUpperCase, passwordStrength.hasLowerCase, passwordStrength.hasNumber, passwordStrength.hasSymbol].filter(Boolean).length >= 3 ? 'valid' : ''}`}>
                                    ✓ 包含大写字母、小写字母、数字、特殊符号中至少三种
                                </div>
                                <div className={`rule ${passwordStrength.noSpace ? 'valid' : ''}`}>
                                    ✓ 不能包含空格
                                </div>
                                <div className={`rule ${passwordStrength.noRepeat && passwordStrength.noConsecutive ? 'valid' : ''}`}>
                                    ✓ 不能有连续或重复的三个及以上字符
                                </div>
                            </div>
                            
                            <div className="form-group password-group">
                                <label htmlFor="confirmPassword">确认密码</label>
                                <div className="password-input-wrapper">
                                    <input
                                        id="confirmPassword"
                                        type={showConfirmPassword ? "text" : "password"}
                                        name="confirmPassword"
                                        value={formData.confirmPassword}
                                        onChange={handleInputChange}
                                        placeholder="请再次输入密码"
                                        disabled={loading}
                                    />
                                    <span
                                        className="toggle-password"
                                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                    >
                                        {showConfirmPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />}
                                    </span>
                                </div>
                                {errors.confirmPassword && (
                                    <span className="error-message">{errors.confirmPassword}</span>
                                )}
                            </div>
                            
                            <button
                                type="submit"
                                className="submit-btn"
                                disabled={loading}
                            >
                                {loading ? "提交中..." : "重置密码"}
                            </button>
                        </form>
                    )}
                </div>
            </div>
        </div>
    )
}